package com.lcb.manager.util;

import com.lcb.manager.configuration.Config;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class MediaUploadUtil {

    public static List<String> uploadImages(MultipartFile[] files) {
        List<String> imageNameList = new ArrayList<>();
        for (MultipartFile file : files) {
            String suffix = "jpg";
            String originalFileName = file.getOriginalFilename();
            if (originalFileName != null) {
                if (originalFileName.contains(".")) {
                    suffix = originalFileName.split("\\.")[1];
                }
                if (originalFileName.contains("/images/")) {
                    String oldFileName = originalFileName.split("images/")[1];
                    imageNameList.add(oldFileName);
                } else {
                    try {
                        byte[] bytes = file.getBytes();
                        String imgName = RandomUtil.getRandomFileName() + "." + suffix;
                        Path path = Paths.get(Config.upload_dir + imgName);
                        Files.write(path, bytes);
                        imageNameList.add(imgName);
                    } catch (IOException e) {
                        System.out.println("file upload error");
                        e.printStackTrace();
                    }
                }
            }
        }
        return imageNameList;
    }

    public static String uploadVideo(MultipartFile[] files) {
        String videoName = "";
        if (files.length > 0) {
            String suffix = "jpg";
            String originalFileName = files[0].getOriginalFilename();
            if (originalFileName != null) {
                if (originalFileName.contains(".")) {
                    suffix = originalFileName.split("\\.")[1];
                }
                if (originalFileName.contains("/images/")) {
                    videoName = originalFileName.split("images/")[1];
                } else {
                    try {
                        byte[] bytes = files[0].getBytes();
                        String imgName = RandomUtil.getRandomFileName() + "." + suffix;
                        Path path = Paths.get(Config.upload_dir + imgName);
                        Files.write(path, bytes);
                        videoName = imgName;
                    } catch (IOException e) {
                        System.out.println("file upload error");
                        e.printStackTrace();
                    }
                }
            }
        }
        return videoName;
    }
}
